﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;

namespace Bot2
{

    class PluginManager<T>
    {
        public static List<T> GetList()
        {
            Assembly ass;
            List<T> lst = new List<T>();
            string [] files = null;
            try
            {

                files = Directory.GetFiles(Directory.GetCurrentDirectory() + "\\.", "*.dll");
            }
            catch (Exception)
            {
                files = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll");
            }
            foreach (string plugin in files )
            {
                try
                {
                    ass = Assembly.LoadFile(plugin);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Skipping " + plugin + " beacuse " + e.Message);
                    continue;
                }
                Console.WriteLine("Analysing " + plugin);
                try
                {
                    foreach (Type t in ass.GetTypes())
                    {
                        if (t.BaseType.ToString() == typeof(T).ToString())
                        {
                            T j;
                            try
                            {
                                j = (T)ass.CreateInstance(t.ToString());
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("Skipping " + plugin + " beacuse " + e.Message);
                                continue;
                            }
                            lst.Add(j);
                        }
                        else Console.WriteLine("Анализ типов: ожидается - " + typeof(T).ToString() + ". Пропуск класса " + t.ToString() + " с типом " + t.BaseType.ToString());
                    }
                }
                catch (ReflectionTypeLoadException e)
                {
                    Console.WriteLine("Skipping " + plugin + " beacuse " + e.Message);
                    foreach (Exception ex in e.LoaderExceptions)
                    {
                        Console.WriteLine("... " + ex.Message);
                    }
                    throw;
                }

            }
            return lst;
        }
    }

}
